<template>
  <div class="imgUpload">
    <el-upload
      action="https://jsonplaceholder.typicode.com/posts/"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :class="{ isShow: isShow }"
      :http-request="send"
      :on-change="handleChange"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <!-- 进度条 -->
    <el-progress
      v-if="showProg"
      style="width:190px"
      :percentage="percent"
    ></el-progress>

    <el-dialog title="图片预览" :visible.sync="showImage">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import COS from "cos-js-sdk-v5";

var cos = new COS({
  SecretId: "AKIDXrviFWWFixwe7KHxNXQ3QWNyJPEm45qK",
  SecretKey: "EDwPbWAXdR2MPAernSqxnMegQt62h5C1"
});
export default {
  name: "imgUpload",
  computed: {
    isShow() {
      return this.fileList.length > 0;
    }
  },
  data() {
    return {
      // 进度条
      percent: 0,
      // 显示进度条
      showProg: false,
      dialogImageUrl: "",
      showImage: false,
      fileList: [] //上传图片的位置
    };
  },
  methods: {
    //   文件状态发生改变时触发
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    // 移出照片钩子函数  参数一为移出的图片信息  参数二为移除后数组里剩下的图片信息
    handleRemove(file, fileList) {
      this.fileList = [];
    },

    // 图片预览钩子
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.showImage = true;
    },
    send(params) {
      this.showProg = true;
      cos.putObject(
        {
          // 腾讯云存储桶名称
          Bucket: "hmhr72-1306790611" /* 必须 */,

          Region: "ap-guangzhou" /* 存储桶所在地域，必须字段 */,
          //   保存的文件名
          Key: params.file.name /* 必须 */,
          //   这个是存储方式，不用修改
          StorageClass: "STANDARD",

          Body: params.file, // 上传文件对象
          // 是一个回调函数， progressData为上传进度
          onProgress: progressData => {
            this.percent = progressData.percent * 100;
          }
        },
        // 成功或失败回调的方法
        (err, data) => {
          if (!err) {
            this.fileList = [{ url: "http://" + data.Location }];
          }
          this.percent = 0;
          this.showProg = false;
        }
      );
    }
  }
};
</script>

<style>
.isShow .el-upload--picture-card {
  display: none;
}
</style>
